package com.itsitio.dbloader.servicio;


import java.util.LinkedList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.itsitio.dbloader.dao.UsuarioDao;
import com.itsitio.dbloader.modelo.usuario.Usuario;

/**
 * SeguridadSrv	
 * @author 
 *
 */
@Service
@Transactional
public class SeguridadSrv implements UserDetailsService{

	@Autowired
	UsuarioDao dao;
	
	/* (non-Javadoc)
	 * @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)
	 */
	@Override
	public UserDetails loadUserByUsername(String codigoIS) throws UsernameNotFoundException, DataAccessException 
	{
		Usuario temp = dao.obtenerPorIS(codigoIS, true);
		System.out.println("alguien se logueo: " + codigoIS);
		
		if(temp == null)
		{
			throw new UsernameNotFoundException("No se encontro el usuario");
		}
		boolean activo = true;
		return  new User(temp.getMail(), temp.getContrasena(), activo, activo, activo,activo,armarAuthorities(temp));
	}
	/**
	 * @param perfiles
	 * @return
	 */
	private List<GrantedAuthority> armarAuthorities(Usuario user) 
	{
		List<GrantedAuthority> result = new LinkedList<GrantedAuthority>();
		if (user.isEsAdmin()){
			result.add(new GrantedAuthorityImpl("Administrador"));
		}
		if (user.isEsLider()){
			result.add(new GrantedAuthorityImpl("Lider"));
		}
		if(!(user.isEsLider()) && !(user.isEsAdmin())){
			result.add(new GrantedAuthorityImpl("Personal"));
		}
		if(user.getSysAdmin()){
			result.add(new GrantedAuthorityImpl("AdministradorSistema"));
		}
		
	System.out.println(result);
	System.out.println(user.getCodigoIS());
		
//		for (Dato perfil : perfiles) 
//		{
//			result.add(new GrantedAuthorityImpl(perfil.getValor()));	
//		}
		return result;
	}

}
